package top.mhtools.pigeon.ding.service.support;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import top.mhtools.pigeon.common.constant.BaseConstant;
import top.mhtools.pigeon.common.exception.ServiceException;
import top.mhtools.pigeon.common.persistence.DingRequest;

import java.util.List;
import java.util.Objects;

/**
 * 钉钉发送消息执行器
 *
 * @author machen
 * @date 2020/4/24 19:22
 */
@Slf4j
public abstract class AbstractDingMessageExecuteStrategy {

    @Value("${dingtalk.url}")
    protected String dingtalkUrl;

    /**
     * 执行方法
     *
     * @param dingRequest
     */
    public abstract void execute(DingRequest dingRequest);

    /**
     * 定义标识
     *
     * @return
     */
    public abstract String supports();

    /**
     * 消息发送
     *
     * @param client
     * @param request
     */
    public void sendMessage(DingTalkClient client, OapiRobotSendRequest request) {
        OapiRobotSendResponse response = null;
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            log.error("  >>> 调用钉钉接口异常 ", e);
            throw new ServiceException("调用钉钉接口异常", e);
        }
        log.info("  >>> 调用钉钉消息接口返回值 :: {}", JSON.toJSONString(response));

        if (!Objects.equals(response.getErrcode(), BaseConstant.SUCCESS_CODE)) {
            throw new ServiceException("调用钉钉接口异常", response.getErrmsg());
        }
    }

    public OapiRobotSendRequest.At buildAt(List<String> atMobiles) {
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setAtMobiles(atMobiles);
        return at;
    }
}
